import {useAtom} from "jotai";
import {
    currentPageAtom,
    pageSizeAtom,
    selectedRangeAtom,
    selectedTypeAtom, sortByCountDescAtom,
    sortByDifficultyDescAtom
} from "../../store/atoms";
import {useEffect, useMemo, useState} from "react";

interface Props {
    className?: string;
}

/**
 * 首页分页组件
 * @param className 扩展
 */
function HomePagePagination({className = ''}: Props) {
    const [currentPage, setCurrentPage] = useAtom(currentPageAtom)
    const [pageSize] = useAtom(pageSizeAtom);
    const [selectedType, setSelectedType] = useAtom(selectedTypeAtom);
    const [selectedRange, setSelectedRange] = useAtom(selectedRangeAtom);
    const [sortByDifficultyDesc, setSortByDifficultyDesc] = useAtom(sortByDifficultyDescAtom);
    const [sortByCountDesc, setSortByCountDesc] = useAtom(sortByCountDescAtom);
    const [totalCount, setTotalCount] = useState(0);
    useEffect(() => {
        window.ipcRender.invoke('db:getQuesCount', {
            type: selectedType,
            rating: selectedRange
        }).then((res: number) => {
            setTotalCount(res);
            setCurrentPage(1);
            console.log("考题总数:", res);
        })
    }, [selectedType, selectedRange, sortByDifficultyDesc, sortByCountDesc]);
    // useMemo，当列表对象改变时才重新计算，优化性能
    const totalPages = useMemo(() => Math.ceil(totalCount / pageSize), [totalCount, pageSize]);
    // 计算显示的页码
    const pageNumbers = useMemo(() => {
        const pages = [];
        let start = 1;
        let end = totalPages;

        if (totalPages <= 5) {// 总页数不足5页，直接全部显示
            start = 1;
            end = totalPages;
        } else if (currentPage <= 3) {// 当前页靠前，显示前5页
            start = 1;
            end = 5;
        } else if (currentPage >= totalPages - 2) {// 当前页靠后，显示最后5页
            start = totalPages - 4;
            end = totalPages;
        } else { // 正常情况，当前页居中
            start = currentPage - 2;
            end = currentPage + 2;
        }
        for (let i = start; i <= end; i++) {
            pages.push(i);
        }
        return pages;
    }, [currentPage, totalPages]);

    const changePage = (page: number) => {
        setCurrentPage(page);
    }

    if (totalPages <= 1) return null;

    return (
        <div className={`w-fit ${className}`}>
            <div className="join m-2">
                <button
                    className="join-item btn"
                    disabled={currentPage === 1}
                    onClick={() => changePage(1)}
                >
                    «
                </button>

                {pageNumbers.map((page) => (
                    <button
                        key={page}
                        className={`join-item btn ${page === currentPage ? 'btn-neutral' : ''}`}
                        onClick={() => changePage(page)}
                    >
                        {page}
                    </button>
                ))}

                <button
                    className="join-item btn"
                    disabled={currentPage === totalPages}
                    onClick={() => changePage(totalPages)}
                >
                    »
                </button>
            </div>
        </div>
    );
}

export default HomePagePagination;